<?php

add_action('admin_head', 'embedLogoJS');

function render_project_logo($post){
	wp_nonce_field(plugin_basename(__FILE__), 'project_logo_nonce'); 
	$img_url = get_post_meta($post->ID, 'dmci_project_logo', true);
	$imgW = get_post_meta($post->ID, 'logoWidth', true);
	$imgH = get_post_meta($post->ID, 'logoHeight', true);
	
	if( !$imgW ){
		$imgW =	'150';
	}
	if ( !$imgH ){
		$imgH = '150';
	}
	$html = '';	
	if($img_url){
		$html .= '<p id="logoPreview"><img src="'.$img_url.'" width="150px" height="150px" /></p>';	
	}
	else{
		$html .= '<p class="description">Upload project logo</p><p id="logoPreview"></p>';
	}
	
	$html .= '<p><input type="hidden" class="metaValueField" id="dmci_project_logo" name="dmci_project_logo" value="'.$img_url.'" />';
	$html .= '<input class="button" id="logoUploadBtn" type="button" value="Choose File" />
			<input class="button remLogo" type="button" value="Remove File" /></p>';
	$html .= '<p><label>Logo Width: </label><input type="text" name="logoWidth" id="logoWidth" value="'.$imgW.'" /></p>';
	$html .= '<p><label>Logo Height: </label><input type="text" name="logoHeight" id="logoHeight" value="'.$imgH.'" /></p>';
	echo $html;
}

function save_project_logo($post_id){
	global $post;
	
	
	if( !isset($_POST['project_logo_nonce']) || !wp_verify_nonce($_POST['project_logo_nonce'], plugin_basename(__FILE__))) {  
		return $post_id;
    } 
	
	if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {  
		return $post_id;
	}
	
	if('dmci_projects' != $_POST['post_type']) {  
      if(!current_user_can('edit_page', $post_id)) {  
	       return $post_id;  
      } 
	} 
	else {  
        if(!current_user_can('edit_page', $post_id)) { 
		     return $post_id;  
        } 
    }

	

	if( $post->post_type == "dmci_projects" ) {
		update_post_meta($post_id, 'dmci_project_logo', esc_attr($_POST['dmci_project_logo'])); 
		update_post_meta($post_id, 'logoWidth', esc_attr($_POST['logoWidth'])); 
		update_post_meta($post_id, 'logoHeight', esc_attr($_POST['logoHeight'])); 
	}
	
}

add_action('save_post', 'save_project_logo');

function embedLogoJS(){
	 ?>
  <script type="text/javascript">
	
	jQuery(document).ready(function() {
		var lgClicked = false;
		var slClicked = false;
		var consClicked = false;
		var file_frame; 
		jQuery('#chooseImgBtn').click(function() {
			/*
			formfield = jQuery('#chooseImgBtn').attr('name');
			tb_show( '', 'media-upload.php?type=image&amp;TB_iframe=true' );
			slClicked = true;
			jQuery("#TB_window").bind('tb_unload', function () {
				slClicked = false;
      		});
			*/
			event.preventDefault();
 			the_uploader(file_frame, 'slider', true)
			
		});
		
		
		jQuery('#logoUploadBtn').click(function() {
			/*formfield = jQuery('#logoUploadBtn').attr('name');
			tb_show( '', 'media-upload.php?type=image&amp;TB_iframe=true' );
			lgClicked = true;
			jQuery("#TB_window").bind('tb_unload', function () {
				lgClicked = false;
      		});*/
			the_uploader(file_frame, 'logo', false)
			return false;
		});
		
		jQuery('#addConsSlide').click(function() {
			/*
			formfield = jQuery('#addConsSlide').attr('name');
			tb_show( '', 'media-upload.php?type=image&amp;TB_iframe=true' );
			consClicked = true;
			jQuery("#TB_window").bind('tb_unload', function () {
				consClicked = false;
      		});*/
			the_uploader(file_frame, 'cons_slider', true);
			return false;
		});
		
		window.original_send_to_editor = window.send_to_editor;
		window.send_to_editor = function(html) {
			
			if( lgClicked ) {
				imgurl = jQuery('img',html).attr('src');
				jQuery('#dmci_project_logo').val(imgurl);
				jQuery('#logoPreview').html('').html('<img src="'+imgurl+'" width="150px" height="150px" />');
				lgClicked = false;
				tb_remove();
			}
			else if( slClicked ) {
					imgurl = jQuery('img',html).attr('src');
					var html = '';
					html += '<div class="simages">';
					html += '<img src="'+imgurl+'" width="150px" height="150px" /><br/>';
					html += '<a href="#" class="button removeSlide">Remove</a>';
					html += '</div>';
					jQuery('#slider_images').append(html);
					checkSlides();
					tb_remove();
			}
			else if( consClicked ){
					
					imgurl = jQuery('img',html).attr('src');
					var html = '';
					html += '<tr>';
					html += '<td><img src="'+ imgurl + '" width="100" height="100"></td>';
					html += '<td><textarea rows="5" cols="100" name="cslide_text[]"></textarea></td>';
					html += '<td><a href="#" class="del-cons-slide button" >Remove</a>';
					html += '<input type="hidden" name="cslide_image[]" value="' + imgurl +'"></td>';
					html += '</tr>';
					jQuery('#consSlideTbody').append(html);
					tb_remove();
			}
			else {
				window.original_send_to_editor(html)	
			}
    	}
		
		
		
		jQuery('.remLogo').click(function (){
			jQuery('#dmci_project_logo').val('');
			jQuery('#logoPreview').html('');
		});
		
		jQuery('.removeSlide').live('click', function (e){
			jQuery(this).parent().remove();
			checkSlides();
			e.preventDefault();
		})
		
		jQuery('.del-cons-slide').live('click', function (e){
			jQuery(this).parent().parent().remove();
			e.preventDefault();
		})
		
		if( jQuery('.datepicker').is(':visible') ){
			jQuery('.datepicker').datepicker();
		}
		
	  });
	  
	  function checkSlides(){
		var images = '';
		var ctr = 0;
		jQuery('.simages').each(function(index, element) {
			var image_src = jQuery(this).find('img').attr('src');
			images += '"' + ctr + '":"' + image_src + '",' ;
			ctr++
		});;
		images = images.substring(0, images.length-1);
		console.log('{'+images+'}');
		jQuery('#dmci_sliders').val('{'+images+'}');
		}
		
		function the_uploader(file_frame, option, m){
			// If the media frame already exists, reopen it.
			if ( file_frame ) {
			  file_frame.open();
			  return;
			}
		 
			// Create the media frame.
			file_frame = wp.media.frames.file_frame = wp.media({
			  title: jQuery( this ).data( 'uploader_title' ),
			  button: {
				text: jQuery( this ).data( 'uploader_button_text' ),
			  },
			  multiple: m  // Set to true to allow multiple files to be selected

			});
		 
			// When an image is selected, run a callback.
			file_frame.on( 'select', function() {
			  // We set multiple to false so only get one image from the uploader
			  attachment = file_frame.state().get('selection').first().toJSON();
		 		console.log(attachment.url);
			  // Do something with attachment.id and/or attachment.url here
			});
		 
			// Finally, open the modal
			file_frame.open();
			
			file_frame.on( 'select', function() {
 
				var selection = file_frame.state().get('selection');
			 
				selection.map( function( attachment ) {
			 
				  attachment = attachment.toJSON();
			 	
				  // Do something with attachment.id and/or attachment.url here
				  if( option == 'logo' ) {
					jQuery('#dmci_project_logo').val(attachment.url);
					jQuery('#logoPreview').html('').html('<img src="'+attachment.url+'" width="150px" height="150px" />');	  
				  }
				  if( option == 'slider' ){
					var html = '';
					html += '<div class="simages">';
					html += '<img src="'+attachment.url+'" width="150px" height="150px" /><br/>';
					html += '<a href="#" class="button removeSlide">Remove</a>';
					html += '</div>';
					jQuery('#slider_images').append(html);
					checkSlides();
				  }
				  
				  if( option == 'cons_slider' ){
					var html = '';
					html += '<tr>';
					html += '<td><img src="'+ attachment.url + '" width="100" height="100"></td>';
					html += '<td><textarea rows="5" cols="100" name="cslide_text[]">'+ attachment.description +'</textarea></td>';
					html += '<td><a href="#" class="del-cons-slide button" >Remove</a>';
					html += '<input type="hidden" name="cslide_image[]" value="' + attachment.url +'"></td>';
					html += '</tr>';
					jQuery('#consSlideTbody').append(html);
				  }
				  
				});
			  });
			
			return false;
			
			
			
		}
  </script>
  
  <style type="text/css" media="all">
  	#slider_images {
		display:block;
		overflow:auto;	
	}
  	.simages {
		float:left;
		margin-right:5px;
	}
  </style>
  <?php 
  
	
}

function save_sliders($post_id){
	global $post;
	
	
	if( !isset($_POST['project_sliders_nonce']) || !wp_verify_nonce($_POST['project_sliders_nonce'], plugin_basename(__FILE__))) {  
		return $post_id;
    } 
	
	if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {  
		return $post_id;
	}
	
	if('dmci_projects' != $_POST['post_type']) {  
      if(!current_user_can('edit_page', $post_id)) {  
	  	return $post_id;  
      } 
	} 
	else {  
        if(!current_user_can('edit_page', $post_id)) { 
			
            return $post_id;  
        } 
    }

	

	if( $post->post_type == "dmci_projects" ) {
		update_post_meta($post->ID, 'dmci_sliders', esc_attr($_POST['dmci_sliders']));
		update_post_meta($post->ID, 'dmci_slider_title', esc_attr($_POST['dmci_slider_title']));
		update_post_meta($post->ID, 'dmci_slider_desc', esc_attr($_POST['dmci_slider_desc']));
	}
	
}

add_action('save_post', 'save_sliders');

function render_project_slider($post){
	wp_nonce_field(plugin_basename(__FILE__), 'project_sliders_nonce'); 
	
	$sliders = get_post_meta($post->ID, 'dmci_sliders', true);
	$slider_title = get_post_meta($post->ID, 'dmci_slider_title', true);
	$slider_desc = get_post_meta($post->ID, 'dmci_slider_desc', true);
	
	$the_slides = json_decode(htmlspecialchars_decode($sliders), true);
	$html = '';
	$html .= '<p><input type="button" class="button" id="chooseImgBtn" value="Choose Images" /></p>';
	$html .= '<div id="slider_images">';
	if( !empty($the_slides) ){
		foreach($the_slides as $s){
		$html .= '<div class="simages"><img src="'.$s.'" width="150px" height="150px"><br><a href="#" class="button removeSlide">Remove</a></div>';
		}
	}
	$html .= '</div>';
	$html .= '<hr/>';
	$html .= '<p><label for="dmci_slider_title">Slider Title: </label><input type="text" name="dmci_slider_title" id="dmci_slider_title" class="widefat" value="'.$slider_title.'"></p>';
	$html .= '<p><label for="dmci_slider_desc">Slider Description:</label><textarea name="dmci_slider_desc" id="dmci_slider_desc" rows="1" cols="40" class="widefat attachmentlinks">'.$slider_desc.'</textarea></p>';
	$html .= '<input type="hidden" value="'.$sliders.'" name="dmci_sliders" id="dmci_sliders" >';
	echo $html;
}



	/* Page Slider */
	
	function save_page_slider($post_id){
		global $post;
		
		
		if( !isset($_POST['dmci_page_slider_nonce']) || !wp_verify_nonce($_POST['dmci_page_slider_nonce'], plugin_basename(__FILE__))) {  
			return $post_id;
		} 
		
		if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {  
			return $post_id;
		}
		
		if('page' != $_POST['post_type']) {  
		  if(!current_user_can('edit_page', $post_id)) {  
			return $post_id;  
		  } 
		} 
		else {  
			if(!current_user_can('edit_page', $post_id)) { 
				
				return $post_id;  
			} 
		}
	
		
	
		if( $post->post_type == "page" ) {
		
			update_post_meta($post->ID, 'dmci_page_slider', esc_attr($_POST['dmci_page_slider']));
			update_post_meta($post->ID, 'dmci_page_slider_title', esc_attr($_POST['dmci_page_slider_title']));
			update_post_meta($post->ID, 'dmci_page_slider_desc', esc_attr($_POST['dmci_page_slider_desc']));
		}
		
	}
	
	add_action('save_post', 'save_page_slider');
	
	function render_page_slider($post){
		wp_nonce_field(plugin_basename(__FILE__), 'dmci_page_slider_nonce'); 
		
		$sliders = get_post_meta($post->ID, 'dmci_page_slider', true);
		$slider_title = get_post_meta($post->ID, 'dmci_page_slider_title', true);
		$slider_desc = get_post_meta($post->ID, 'dmci_page_slider_desc', true);
		
		$the_slides = json_decode(htmlspecialchars_decode($sliders), true);
		$html = '';	
		$html .= '<p><input type="button" class="button" id="chooseImgBtn" value="Choose Images" /></p>';
		$html .= '<div id="slider_images">';
		if( !empty($the_slides) ){
			foreach($the_slides as $s){
			$html .= '<div class="simages"><img src="'.$s.'" width="150px" height="150px"><br><a href="#" class="button removeSlide">Remove</a></div>';
			}
		}
		$html .= '</div>';
		$html .= '<hr/>';
		$html .= '<p><label for="dmci_page_slider_title">Slider Title: </label><input type="text" name="dmci_page_slider_title" id="dmci_slider_title" class="widefat" value="'.$slider_title.'"></p>';
		$html .= '<p><label for="dmci_page_slider_desc">Slider Description:</label><textarea name="dmci_page_slider_desc" id="dmci_page_slider_desc" rows="1" cols="40" class="widefat attachmentlinks">'.$slider_desc.'</textarea></p>';
		$html .= '<input type="hidden" value="'.$sliders.'" name="dmci_page_slider" id="dmci_sliders" >';
		echo $html;
	}

	/* Constuction Update Slider */
	function render_cons_slider($post){
		wp_nonce_field(plugin_basename(__FILE__), 'dmci_cons_slider_nonce'); 
		
		$slides = get_post_meta($post->ID, 'cons_slide', true);
		$tr = '';
		
		if( !empty($slides) ) {
		foreach($slides as $slide){
			$tr .= '<tr>
				<td><img src="'.$slide['image'].'" width="100" height="100" ></td>
				<td><textarea name="cslide_text[]" rows="5" cols="100">'.$slide['text'].'</textarea></td>
				<td>
					<a href="#" class="del-cons-slide button" >Remove</a>
					<input type="hidden" name="cslide_image[]" value="'.$slide['image'].'">
				</td>
			</tr>';
		}
		}
		$html = '';
		$html .= '<p><input type="button" class="button" id="addConsSlide" value="Add Images" /></p>';
		$html .= '<table class="wp-list-table widefat">
				<thead>
					<tr>
						<th>Image</th>
						<th>Description</th>
						<th>Remove</th>
					</tr>
				</thead>
				<tfoot>
					<tr>
						<th>Image</th>
						<th>Description</th>
						<th>Remove</th>
					</tr>
				</tfoot>
				<tbody id="consSlideTbody">
					'.$tr.'
				</tbody>
			</table>';
		echo $html;
		
	}
	
	
	function save_cons_slider($post_id){
		global $post;
		
		
		if( !isset($_POST['dmci_cons_slider_nonce']) || !wp_verify_nonce($_POST['dmci_cons_slider_nonce'], plugin_basename(__FILE__))) {  
			return $post_id;
		} 
		
		if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {  
			return $post_id;
		}
		
		if('dmci_cons_update' != $_POST['post_type']) {  
		  if(!current_user_can('edit_page', $post_id)) {  
			return $post_id;  
		  } 
		} 
		else {  
			if(!current_user_can('edit_page', $post_id)) { 
				
				return $post_id;  
			} 
		}
	
		
	
		if( $post->post_type == "dmci_cons_update" ) {
			
			$image = $_POST['cslide_image'];
			$text = $_POST['cslide_text'];
			$data = array();
			for( $i = 0 ; $i < count($image) ; $i++ ){
				$data[$i]['image'] = $image[$i];
				$data[$i]['text'] = $text[$i];
			}
			
			update_post_meta($post->ID, 'cons_slide', $data);
			
		}
		
	}
	
	add_action('save_post', 'save_cons_slider');

	/* End Construction Update Slider */


	


